import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class BannerComponent extends StatefulWidget {
  final int duration; // 间隔时间
  final int scrollTime; // 滑动耗时 毫秒
  final double height; // banner 高度
  int _index = 0;
  final List<Widget> data;
  BannerComponent(
      {Key key,
      @required this.data,
      this.duration = 3,
      this.scrollTime = 500,
      this.height = 160})
      : super(key: key);
  @override
  _BannerComponentState createState() => _BannerComponentState();
}

class _BannerComponentState extends State<BannerComponent> {
  PageController controller = new PageController();
  Timer timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    resetTimer();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    clearTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        _builderBanner(),
      ],
    );
  }

  Widget _builderBanner() {
    return new SizedBox(
      width: MediaQuery.of(context).size.width,
      height: widget.height,
      child: new GestureDetector(
        onTapDown: (details) {
          clearTimer();
        },
        onTapUp: (details) {
          resetTimer();
        },
        onTapCancel: () {
          resetTimer();
        },
        onTap: () {
          resetTimer();
        },
        child: new PageView.builder(
          itemCount: 0x7fffffff,
          itemBuilder: (BuildContext context, int index) {
            return widget.data[index % widget.data.length];
          },
          controller: controller,
          physics:
              const PageScrollPhysics(parent: const BouncingScrollPhysics()),
          onPageChanged: (index) {
            setState(() {
              widget._index = index;
            });
          },
        ),
      ),
    );
  }

  resetTimer() {
    clearTimer();
    timer = new Timer.periodic(new Duration(seconds: widget.duration),
        (Timer timer) {
      if (controller.positions.isNotEmpty) {
        widget._index = controller.page.round() + 1;

        controller.animateToPage(widget._index,
            curve: Curves.linear,
            duration: new Duration(microseconds: widget.scrollTime));
        setState(() {});
      }
    });
  }

  clearTimer() {
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }
}
